package com.android.lib.base.ext

import android.graphics.Outline
import android.view.View
import android.view.ViewOutlineProvider
import com.blankj.utilcode.util.SizeUtils

/**
 *
 * description:
 * <pre>
 *      View扩展
 * </pre>
 **/
/**
 * 防止重复点击
 * @param interval 重复间隔
 * @param onClick  事件响应
 */
var lastTime = 0L
fun View.click(interval: Long = 400, onClick: (View) -> Unit) {
    setOnClickListener {
        val currentTime = System.currentTimeMillis()
        if (lastTime != 0L && (currentTime - lastTime < interval)) {
            return@setOnClickListener
        }
        lastTime = currentTime
        onClick(it)
    }
}

///***
// * 点击事件的View扩展
// * @param block: (T) -> Unit 函数
// * @return Unit
// */
//@Suppress("UNCHECKED_CAST")
//fun <T : View> T.click(block: (T) -> Unit) = setOnClickListener {
//    block(it as T)
//}

/**
 * 设置长按监听
 */
fun View.longClick(action: (view: View) -> Boolean) {
    setOnLongClickListener {
        action(it)
    }
}

fun View.chip(radius: Int) {
    outlineProvider = object : ViewOutlineProvider() {
        override fun getOutline(view: View?, outline: Outline?) {

            outline?.setRoundRect(
                0,
                0,
                view?.width ?: 0,
                view?.height ?: 0,
                SizeUtils.dp2px(radius.toFloat()).toFloat()
            )
        }
    }
    clipToOutline = true
}

fun View.chipTop(radius: Int) {
    outlineProvider = object : ViewOutlineProvider() {
        override fun getOutline(view: View?, outline: Outline?) {
            outline?.setRoundRect(
                0,
                0,
                view?.width ?: 0,
                view?.height?.plus(SizeUtils.dp2px(radius.toFloat())) ?: 0,
                SizeUtils.dp2px(radius.toFloat()).toFloat()
            )
        }
    }
    clipToOutline = true
}

fun View.chipBottom(radius: Int) {
    outlineProvider = object : ViewOutlineProvider() {
        override fun getOutline(view: View?, outline: Outline?) {
            outline?.setRoundRect(0, -radius, view?.width ?: 0, view?.height ?: 0, radius.toFloat())
        }
    }
    clipToOutline = true
}


/*** 可见性相关 ****/
fun View.gone() {
    visibility = View.GONE
}

fun View.visible() {
    visibility = View.VISIBLE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

val View.isGone: Boolean
    get() {
        return visibility == View.GONE
    }

val View.isVisible: Boolean
    get() {
        return visibility == View.VISIBLE
    }

val View.isInvisible: Boolean
    get() {
        return visibility == View.INVISIBLE
    }

/**
 * 切换View的可见性
 */
fun View.toggleVisibility() {
    visibility = if (visibility == View.GONE) View.VISIBLE else View.GONE
}

